<template>
  <div :class="[{'single-up-down': isUpDown}]">
    <el-upload v-loading="loading" v-if="!disabled" :disabled="(modelValue !== '' && modelValue !== null)" :class="['pic-uploader-component', modelValue || diyBackground? 'no-border':'']"
      :style="{width: width + 'px', height:  (height? height:width) + 'px'}"
      :action="resourcesUrl +'api/file/upload'" :headers="{ Authorization: token}"
      :show-file-list="false" :on-success="handleUploadSuccess" :before-upload="beforeAvatarUpload" :on-progress="handleProgress">
      <img v-if="modelValue" :src="modelValue" class="pic" :style="{width: width + 'px', height: (height? height:width) + 'px', lineHeight: (height? height:width) +'px'}">
      <span v-if="modelValue && !isImgSee" class="upload-wrapper-del del" @click.stop="handleRemove">
        <i class="el-icon-delete"></i>
      </span>
      <img v-else-if="!modelValue && diyBackground" :src="diyBackground" :style="{width: width + 'px', height: (height? height:width) + 'px'}" />
      <i v-else class="el-icon-plus pic-uploader-icon" v-show="!isImgSee" :style="{width: width + 'px', height: (height? height:width) + 'px', lineHeight: (height? height:width) +'px'}"></i>
    </el-upload>
    <img v-else :src="modelValue" :style="{width: width + 'px', height:  (height? height:width) + 'px', borderRadius: '4px'}" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      resourcesUrl: '',
      token: '',
      loading: false
    }
  },
  props: {
    value: {
      default: '', 
      type: [String, Object]
    },
    // 文件大小
    limitSize: {
      default: 10,
      type: [Number, String]
    },
    // 是否校验比例
    sizeVisible: {
      default: false,
      type: Boolean
    },
    // 占位大小
    width: {
      default: 94,
      type: [Number, String]
    },
    height: {
      default: 94,
      type: [Number, String]
    },
    // 比例
    proportion: {
      default: 1,
      type: [Number, String]
    },
    // 自定义背景图
    diyBackground: {
      type: String,
      defalut: () => ''
    },
    // 是否禁止点击
    disabled: {
      type: Boolean,
      defalut: () => false
    },
    // 是否是详情
    isImgSee:{
      type: Boolean,
      defalut: () => false
    },
    // 是否上下结构
    isUpDown: {
      type: Boolean,
      defalut: () => false
    }
  },
  computed: {
    modelValue() {
      console.log(this.value, '------------ value');
      if (typeof(this.value) == 'string') {
        return this.value
      } else if (typeof(this.value) == 'object') {
        if (this.value.fileUrl) {
          return this.value.fileUrl
        } else {
          return ''
        }
      }
    }
  },
  created() {
    this.resourcesUrl = process.env.VUE_APP_BASE_API
    this.token = 'bearer ' + localStorage.getItem('token')
  },
  methods: {
    handleUploadProgress(e, file, fileList) {
      this.loading = true
    },
    handleUploadError(err, file, fileList) {
      this.loading = false
    },
    // 图片上传
    handleUploadSuccess(response, file, fileList) {
      this.loading = false
      if (file.response.code === 200) {
        console.log(file.response)
        this.$emit('input', file.response.data)
      } else {
        this.$message.error('上传图片失败');
      }
    },
    // 图片上传
    handleProgress(){
      this.$emit('change', '')
    },
    // 限制图片上传大小
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < parseInt(this.limitSize)
      if (!isLt2M) {
        this.$message.error(`上传头像图片大小不能超过 ${this.limitSize}MB!`)
        return false
      }
      if (this.sizeVisible) {
        const isSize = new Promise(function (resolve, reject) {
          let _URL = window.URL || window.webkitURL
          let image = new Image()
          image.onload = function () {
            console.log(77, image.width, image.height)
            let valid = image.width / image.height === (this.proportion || 1)
            valid ? resolve() : reject()
          }
          image.src = _URL.createObjectURL(file)
        }).then(
          () => {
            return file
          },
          () => {
            this.$message.error('上传头像图片尺寸不符合')
            return Promise.reject(false)
          }
        )
        let typeArr = file.name.split('.');
        const fileType = (typeArr[typeArr.length - 1]).toLowerCase();
        const fileTypeStr = 'jpg,png,jpeg';
        if (fileTypeStr.indexOf(fileType) < 0) {
          this.$message.warning('图片格式只能为jpg或png');
          return false;
        }
        return isSize
      } else {
        let typeArr = file.name.split('.');
        const fileType = (typeArr[typeArr.length - 1]).toLowerCase();
        const fileTypeStr = 'jpg,png,jpeg';
        if (fileTypeStr.indexOf(fileType) < 0) {
          this.$message.warning('图片格式只能为jpg或png');
          return false;
        }
      }
      return isLt2M
    },
    // 移除
    handleRemove(file, fileList) {
      this.$emit('input', typeof(this.value) == 'string'? '' : { fileUrl: '' })
    }
  }
}
</script>

<style lang="scss">
.single-up-down{
  padding-top: 40px;
}
.no-border .el-upload{
  border: none !important;
}
.pic-uploader-component .el-upload {
  border: 1px solid #DCDFE6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  .pic-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }

  .pic {
    width: 148px;
    height: 148px;
    display: block;
  }
}

.pic-uploader-component {
  width: 148px;
  height: 148px;
  margin-bottom: 2px;
}

.pic-uploader-component .el-upload:hover {
  border-color: #409EFF;
}

.upload-wrapper-del.del {
  position: absolute !important;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background: rgba($color: #000000, $alpha: .5);
  display: flex;
  align-items: center;
  justify-content: center;

  i {
    color: #fff;
    font-size: 18px;
  }
}
</style>
